<?php

require(ROOT . '/controllers/CommonController.class.php');

class PlanController extends CommonController {

	public function __construct() {
		parent::__construct(__CLASS__);

		$this->db = DB::open('reading');
	}

	public function indexAction($segments) {
		$this->layout('layout');
		$this->assign('title', '天行健，君子以自强不息；地势坤，君子以厚德载物。');
		$sql = "select p.*,b.name as book_name from plan p left join book b on p.book=b.id";
		$plans = $this->db->query($sql);
		$this->assign('plans', $plans);
		$this->rend('index');
	}

	public function newAction($segments) {
		$sql = "select id,name from book";
		$books = $this->db->query($sql);
		$this->assign('books', $books);
		$this->rend('new');
	}

	public function insertAction($segments) {
		$data = array(
			'name' => requestPost('name'),
			'book' => requestPost('book'),
			'start' => strtotime(requestPost('start')),
			'end' => strtotime(requestPost('end')),
			'created_at' => time()
		);

		$bookModel = new Model('plan', $this->db);

		if ($bookModel->insert($data)) {
			setFlash('success', 'successful');
		} else {
			setFlash('error', 'error');
		}

		redirect(url('plan/index'));
	}

	public function editAction($segments) {
		$id = intval($segments[0]);

		$sql = "select * from plan where id={$id} limit 1";

		$plan = $this->db->find($sql);

		$this->assign('plan', $plan);

		$sql = "select id,name from book";

		$books = $this->db->query($sql);

		$this->assign('books', $books);

		$this->rend('edit');
	}

	public function updateAction() {
		$id = intval(requestPost('id'));

		$planModel = new Model('plan', $this->db);

		if (!($plan = $planModel->find($id))) {
			echo 'not exsits!';
			exit();
		}

		$data = array(
			'id' => $id,
			'name' => requestPost('name'),
			'book' => requestPost('book'),
			'start' => requestPost('end'),
			'end' => requestPost('end')
		);

		if ($_FILES['cover']['error'] == 0) {
			$path = ROOT . '/assets/upload/' . $book['cover'];
			if (file_exists($path)) {
				unlink($path);
			}

			$this->uploadFile($_FILES['cover']);

			$data['cover'] = $_FILES['cover']['name'];
		}

		if ($planModel->update($data)) {
			setFlash('success', 'successful');
		} else {
			setFlash('error', 'error');
		}
		redirect(url('plan/index'));
	}

	public function deleteAction($segments) {
		$id = intval($segments[0]);

		$bookModel = new Model('plan', $this->db);

		if ($bookModel->delete($id)) {
			setFlash('success', 'delete successful');
		} else {
			setFlash('error', 'delete error');
		}

		redirect(url('plan/index'));
	}

}